package com.boss.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import com.beidouapp.exception.BusinessException;

public class HttpUtils {

	public static String getLocalIpAddress() {
		try {
			return InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String post(String uri, Map<String, Object> params)
			throws IOException {
		return post(uri, params, "utf-8", null);
	}

	public static String postJSON(String uri, Map<String, Object> params)
			throws IOException {
		return post(uri, params, "utf-8", "json");
	}
	
	public static String get(String uri, Map<String, Object> params)
			throws IOException {
		return get(uri, params, "utf-8", null);
	}

	public static String getJSON(String uri, Map<String, Object> params)
			throws IOException {
		return get(uri, params, "utf-8", "json");
	}

	public static String post(String uri, Map<String, Object> params,
			String encoding, String type) throws IOException,BusinessException {

		URL postUrl = new URL(uri);
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		connection.setUseCaches(false);
		connection.setRequestProperty("Accept-Charset", encoding);
		connection.setInstanceFollowRedirects(true);
		connection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		connection.connect();
		String line;
		StringBuffer result = new StringBuffer();
		try {
			OutputStreamWriter out = new OutputStreamWriter(
					connection.getOutputStream(), encoding);
			// new OutputStreamWriter(out)
			StringBuffer content = new StringBuffer();
			if (!"json".equals(type)) {
				Object[] arrays = params.entrySet().toArray();
				for (int index = 0; index < arrays.length; index++) {
					@SuppressWarnings("unchecked")
					Entry<String, Object> value = (Entry<String, Object>) arrays[index];
					Object target = value.getValue();
					if (target instanceof Collection) {
						@SuppressWarnings({ "rawtypes" })
						Object array[] = ((Collection) target).toArray();
						for (int i = 0; i < array.length; i++) {
							content.append(value.getKey() + "="
									+ (String) array[i]);
							if (i <= array.length - 1) {
								content.append("&");
							}
						}
						continue;
					} else {
						if (target != null) {
							content.append(value.getKey() + "="
									+ target.toString());
						}
					}

					if (index <= arrays.length - 1) {
						content.append("&");
					}
				}
			} else {
				content.append(net.sf.json.JSONObject.fromObject(params)
						.toString());
			}
			out.write(content.toString());
			out.flush();
			out.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream(),"UTF-8"));

			while ((line = reader.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
          throw new BusinessException(e.getMessage());
		} finally {
			try {
				connection.disconnect();
			} catch (Exception e) {
				// ignore
			}
		}

		return result.toString();

	}
	
	
	public static String get(String uri, Map<String, Object> params,
			String encoding, String type) throws IOException,BusinessException {

		URL postUrl = new URL(uri);
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("GET");
		connection.setUseCaches(false);
		connection.setRequestProperty("Accept-Charset", encoding);
		connection.setInstanceFollowRedirects(true);
		connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		connection.connect();
		String line;
		StringBuffer result = new StringBuffer();
		try {
			OutputStreamWriter out = new OutputStreamWriter(
					connection.getOutputStream(), encoding);
			// new OutputStreamWriter(out)
			StringBuffer content = new StringBuffer();
			if (!"json".equals(type)) {
				Object[] arrays = params.entrySet().toArray();
				for (int index = 0; index < arrays.length; index++) {
					@SuppressWarnings("unchecked")
					Entry<String, Object> value = (Entry<String, Object>) arrays[index];
					Object target = value.getValue();
					if (target instanceof Collection) {
						@SuppressWarnings({ "rawtypes" })
						Object array[] = ((Collection) target).toArray();
						for (int i = 0; i < array.length; i++) {
							content.append(value.getKey() + "="
									+ (String) array[i]);
							if (i <= array.length - 1) {
								content.append("&");
							}
						}
						continue;
					} else {
						if (target != null) {
							content.append(value.getKey() + "="
									+ target.toString());
						}
					}

					if (index <= arrays.length - 1) {
						content.append("&");
					}
				}
			} else {
				content.append(net.sf.json.JSONObject.fromObject(params)
						.toString());
			}
			out.write(content.toString());
			out.flush();
			out.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream(),"UTF-8"));

			while ((line = reader.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
          throw new BusinessException(e.getMessage());
		} finally {
			try {
				connection.disconnect();
			} catch (Exception e) {
				// ignore
			}
		}

		return result.toString();

	}

	public static void main(String[] args) throws Exception {
	}
}